<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class UserAction extends NewzanAction
{	
	public function login($value='')
	{
		$source_login = 'bos';

		$isGuest = preg_match('/@guest/', $this->_server('QUERY_STRING'));
		if($isGuest === 1) {
			$express['nick'] = '山地肉铺社';
            $express['source'] = 'guest';
            $express['_t'] = time();
            $encrypted_auth_token = base64_encode(authcode(http_build_query($express), 'ENCODE'));
            $loginUrl = 'http://simba.shelpe.com/login?encrypted_auth_token=' . $encrypted_auth_token;
            redirect($loginUrl);
			exit();
		}

		$is_admin = I('admin');
		$is_admin = ($is_admin && strtolower($is_admin) == 'lifuwen') ? true : false;

		$auth_token = base64_decode(I('encrypted_auth_token'));
		if(!$auth_token && $is_admin) {
			import("@.Library.TaobaoAPI.taobaoAuth");
			$oauth = new taobaoAuth();
			$oauth->setAppKey(TB_AKEY2, TB_SKEY2, AUTH_CALLBACK_URL2);
			$this->requestCodeUrl =  $oauth->requestCode();
			redirect($this->requestCodeUrl);
			exit();
			$this->is_admin = $is_admin;
			$this->display();
			exit();
		}
		
		if(!$auth_token) {
			$this->error = '请使用是业务操作系统登录云智投，谢谢！';
			$this->display(TMPL_PATH . 'error.html');
			exit();
		}

		$express = authcode($auth_token);
		parse_str($express, $userLogin);
		$current_time = time();
		if(!$userLogin || (int)$userLogin['_t'] < $current_time - 3600 || ($userLogin['source'] != SSOSROUCE && $userLogin['source'] != "guest") ) {
			$this->error = 'Token过期，请刷新业务稍作系统重新生成Token';
			$this->display(TMPL_PATH . 'error.html');
			exit();
		}

		isset($userLogin['source_login']) && $source_login = $userLogin['source_login'];

		$nick = urldecode(trim($userLogin['nick']));
		$whr = array('nick' => $nick);
		$current_user = D('User')->where($whr)->find();
		if(!$current_user) {
			$this->error = "用户不存在，请绑定用户：{$nick}";
			$this->display(TMPL_PATH . 'error.html');
			exit();
		}

		// 获取当前登录账户的代理账户信息
		$current_manager = D('User')->where('user_id = ' . $current_user['authorized_to'])->find();

		if(!$current_user['authorized_to'])
			$user_id = $current_user['user_id'];
		else 
			$user_id = $current_user['authorized_to'];
		// 获取当前登录账户的代理账户信息登录信息
		$oauth = D('oauth')->where('taobao_user_id = ' . $user_id)->find();
		if(empty($oauth)) {
			$this->error = "找不到该用户oauth授权";
			$this->display(TMPL_PATH . 'error.html');
			exit();
		}
		$current_user['oauth'] = $oauth;
		$current_manager['oauth'] = $oauth;
		session('me', $current_user);
		session('manager', $current_manager);
		
		if($current_user['type']) {
			// 更新用户的购买版本和时间，检查是否购买
	        $version = D('User')->getUserSubScribe($current_user['nick'], ARTICLE_CODE);
	        if($version) {
	        	$userMdl = new UserModel;
	        	if($current_user['purchase_expires'] != $version['deadline'] || $current_user['item_code'] != $version['item_code']) {
		        	$data = array(
		        			'user_id' => $current_user["user_id"],
		        			'purchase_expires' => $version['deadline'],
		        			'item_code' => $version['item_code']
		        	);
	        	}
	        	session("ztc_version", $version);
	        }
		}
		
		require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
		$this->getAccountToken($this->me['user_id'], new Curl());
		R('Home/Index/userLoginrecord', array('source'=>$source_login));

		redirect('/');
	}

	public function refresh(){
		$user_id =  $this->_get("user_id");
		$oauth = D('oauth')->where('taobao_user_id='.$user_id)->find();

		if($oauth && $oauth["refresh_token"]){
			$refresh_token = $oauth["refresh_token"];
			import("@.Library.TaobaoAPI.taobaoAuth");
			$oauth_api = new taobaoAuth();
			$oauth_record = $oauth_api->refreshToken($refresh_token);
			var_dump($oauth_record);
			if(!$oauth_record) {
				$this->error("登录出现了异常哦");
			}
			$oauth_record["oauth_time"] = time();
			$oauth_record["taobao_user_nick"] = rawurldecode($oauth["taobao_user_nick"]);
			$oauth_record["taobao_user_id"] = $oauth['user_id'];
			$oauth_id = D('oauth')->add($oauth_record , array() , true);
			echo $oauth_id;
		}
	}

	public function sync(){
		$user_id =  $this->_get("user_id");
		$original_oauth_record = D('oauth')->where('taobao_user_id='.$user_id)->find();
		if($original_oauth_record && $original_oauth_record["expires_in"] > 0 && $original_oauth_record["oauth_time"] > 0
			&& ($original_oauth_record["oauth_time"] + $original_oauth_record["expires_in"]) > time()){
			require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
			$curl = new Curl();
			$url = build_url("simbascheduler/tenants/{$user_id}");
			$resp = $curl->get($url);
			if($curl->httpStatusCode != 200) {
				throw new NewzanException('系统错误：'.$resp->message, 1);
			}
		}else{
			throw new NewzanException('Session Key过期了', 1);
		}
	}

	public function code()
	{
		session('me' , null);
		session('manager' , null);
		session('shop_status' , null);
		session("ztc_version" , null);
		$isNewUser = false;

		$allowModel = array('system', 'custom');

		$model = strtolower(trim($this->_get("model")));
		$code = $this->_get("code");
		$error = $this->_get('error');
		$error_description = $this->_get('error_description');

		$model = (!$model || !in_array($model, $allowModel)) ? 'system' : $model;
		
		if(!$code){
			$msg = "淘宝认证异常。返回的code为：{$code}。错误信息：{$error}，错误描述：{$error_description}";
			$this->error($msg);
		}

		import("@.Library.TaobaoAPI.taobaoAuth");
		$oauth = new taobaoAuth();
		$userMdl = new UserModel();

		switch ($model) {
			case 'system':
				$oauth->setAppKey(TB_AKEY2, TB_SKEY2, AUTH_CALLBACK_URL2);
				break;
			case 'custom':
				break;
		}

		try {
			$oauth_record = $oauth->requestToken($code);
		} catch(Exception $e) {
			throw new OauthException($e->getMessage());
		}

		if(!$oauth_record) {
			$this->error("登录出现了异常哦");
		}
//		$oauth_record = D('oauth')->where(array('taobao_user_id' => 2977076690))->find();

		//更新oauth表
		$oauth_record["oauth_time"] = time();
		$oauth_record["taobao_user_nick"] = rawurldecode($oauth_record["taobao_user_nick"]);
		$tb_user_id = $oauth_record["taobao_user_id"];
		$oauthSaveData = array(
				'taobao_user_id' => $oauth_record['taobao_user_id'],
				're_expires_in' => $oauth_record['re_expires_in'],
				'r2_expires_in' => $oauth_record['r2_expires_in'],
				'w1_expires_in' => $oauth_record['w1_expires_in'],
				'w2_expires_in' => $oauth_record['w2_expires_in'],
				'expires_in' => $oauth_record['expires_in'],
				'refresh_token' => $oauth_record['refresh_token'],
				'access_token' => $oauth_record['access_token'],
				'oauth_time' => $oauth_record['oauth_time'],
				'r2expires_in' => $oauth_record['r2expires_in'],
				'w1expires_in' => $oauth_record['w1expires_in'],
				'w2expires_in' => $oauth_record['w2expires_in']
			);
		if(D('oauth')->where(array('taobao_user_nick' => $oauth_record['taobao_user_nick']))->count() > 0) {
			D('oauth')->where(array('taobao_user_nick' => $oauth_record['taobao_user_nick']))->save($oauthSaveData);
		} else {
			$oauthSaveData['taobao_user_nick'] = $oauth_record['taobao_user_nick'];
			D('oauth')->add($oauthSaveData, array(), true);
		}

		$nick = $oauth_record['taobao_user_nick'];
		$internal = mb_strpos($nick, 'tp_十禾') !== false || mb_strpos($nick, 'amp_十禾') !== false;
		$existentUser = $userMdl->where(array('nick' => $oauth_record["taobao_user_nick"]))->find();

		//第一次登录
		if(!$existentUser) {
			//初始化用户和相关表
			$userMdl->startTrans();
			try {
				$data = array(
					'user_id' => $oauth_record['taobao_user_id'],
					'nick' => $oauth_record['taobao_user_nick'],
					'user_type' => 1,
					'shop_score' => '',
					'updated_time' => date("Y-m-d H:i:s"),
					'created_time' => date("Y-m-d H:i:s"),
					'type' => '',
					'avatar' => DEFAULT_AVATAR,
					'other' => '',
					'status' => 0,
					'sale' => ''
				);
				session("me", array('nick'=>$oauth_record["taobao_user_nick"]));
				$data['authorized_to'] = $data['user_id'];
				$data['user_type'] = 1;
				$userMdl->addUser($data);
				$userMdl->createTable($tb_user_id);
				$userMdl->commit();
			} catch (Exception $e){
				$userMdl->rollback();
				$this->error($e->getMessage());
			}

			//尝试同步代理账号
			$data = array(
				'user_id' => $oauth_record['taobao_user_id']
			);
			$data['authorized_users'] = $userMdl->getAuthorizedUsers($oauth_record);
			if($data['authorized_users']) {
				$userMdl->save($data);
			}
		}

		//更新用户信息
		$GLOBALS['IS_AGENT'] = in_array($oauth_record["taobao_user_id"], C('AGENT_USER_ID'));
		try {
			$userInfo = $userMdl->getUserByApi($oauth_record, $oauth_record["taobao_user_nick"]);
			$shop_info = $userInfo['user'];
			$data = array(
				'user_id' => $existentUser['user_id'],
				'shop_score' => json_encode((array)$shop_info->seller_credit),
				'updated_time' => date("Y-m-d H:i:s"),
				'type' => isset($shop_info->type) ? $shop_info->type : '',
				'avatar' => isset($shop_info->avatar) ? $shop_info->avatar : DEFAULT_AVATAR,
				'other' => json_encode($shop_info),
				'authorized_to' => 0,
				'user_type' => 1
			);
			if($internal){
				$data['user_type'] = 3;
			}
			$userMdl->save($data);
		} catch (TopClientException $e) {
			if('isv.shop-not-exist:invalid-shop' != getTopErrorSubCode($e->getMessage())) {
				throw $e;
			}
		}

		//处理有代理账号的用户
		$user = $userMdl->getUserByTaobaoId($oauth_record["taobao_user_id"]);
		if($user['authorized_users']) {
			$data = array(
					'user_id' => $existentUser['user_id'],
					'type' => ''
				);
			$user['type'] = '';
			$userMdl->save($data);
			
			if($internal === false) {
				session('me' , null);
	    		session('ztc_version', null);
	    		throw new NewzanException('本服务暂不支持代理帐号，请联系客服获取更多相关信息' , RetStatus::ACCESS_DENY);
			} else {
				$user["oauth"] = $oauth_record;
		        // $this->me = $user;
		        session("me", $user);
	   			session('manager' , $user);
	   			session('admin', true); 
	    		redirect('/user/authusers?forcefresh=1');
			}
		}

		$user["oauth"] = $oauth_record;
		$this->me = $user;
        session("me", $user);

        require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
    	$curl = new Curl();

		//订购用户登录处理
    	if($internal === false) {
        	// 更新用户的购买版本和时间，检查是否购买
	        $version = $userMdl->getUserSubScribe($user['nick'], ARTICLE_CODE);
	        if(empty($version)) {
	        	session('shop_status' , SHOP_STATUS::NO_SERVER);
	        	$this->error("您尚未购买本服务，不能使用");
	        }
        	if($existentUser['purchase_expires'] != $version['deadline'] || $existentUser['item_code'] != $version['item_code']) {
	        	$data = array(
	        			'user_id' => $oauth_record["taobao_user_id"],
	        			'purchase_expires' => $version['deadline'],
	        			'item_code' => $version['item_code']
	        	);
	        	$userMdl->save($data);
        	}
	        session("ztc_version", $version);

        	// 第一次登录需要同步数据
        	if((int)$user['init'] === 0) {
	        	$url = build_url("simbascheduler/tenants/{$user['user_id']}");
	        	$resp = $curl->get($url);
	        	if($curl->httpStatusCode != 200) {
	        		throw new NewzanException('系统错误：'.$resp->message, 1);
	        	} else {
	        		$userMdl->save(array('user_id'=> $user['user_id'], 'init' => 1));
	        	}
	        }
        }

        $this->getAccountToken($user['user_id'], $curl);
        R('Home/Index/userLoginrecord', array('source'=>'code'));
        session('manager' , $user);
    	redirect('/');
	}
    
	/**
	 * 更新当前用户的授权用户列表(包括session和本地db).
	 *  如果给定参数$_GET['fresh']=true, 则强制API获取, 否则从session中读取.
	 */
	public function authusers()
	{
		$manager = session('manager');
		if(!$manager) {
		    $last_visited_url = cookie('last_request_url');
        	if( $last_visited_url ){
        	    redirect($last_visited_url);
        	}else{
        	    redirect('/');
        	}
		}
		
		$forceRefresh = $this->_request('forcefresh') &&
				(strtolower($this->_request('forcefresh')) == 'true' || $this->_request('forcefresh') == 1)
				? true : false;
		if($forceRefresh) {
			$existentAuthUserIds = $manager['authorized_users'] 
					? (is_array($manager['authorized_users']) ? $manager['authorized_users'] : explode(',', $manager['authorized_users']))
					: array();
			
			$userMdl = new UserModel();
			$userMdl->startTrans();
			try {
				// 利用api查询当前所有授权用户
				$apiAuthUserNicks = $userMdl->getAuthorizedUsers();
				
				// 将新授权用户插入数据库
				// $newAuthUsers = array_diff($apiAuthUserNicks, $existentAuthUserIds);
				$allUserIds = $userMdl->saveAuthUsers($apiAuthUserNicks, $manager);

				// 将不再被授权的用户的authorized_to字段重置  
				$deletedAuthUsers = array_diff($existentAuthUserIds, $allUserIds);
				if($deletedAuthUsers) {
					$whr = array();
					$whr['authorized_to'] = array('eq', $manager['user_id']);
					$whr['user_id']  = array('in', $deletedAuthUsers);
					$res = $userMdl->where($whr)->delete(); //save(array('authorized_to'=>0));
					if($res === false) {
						throw_exception('DB异常: '. $userMdl->getDbError());
					}
				}

				// 懒方法: 从数据库中获取更新后的授权用户. 也可以使 $apiAuthUserNicks加saveAuthUsers()返回的ID来组装.
				// 或者使用 select user_id, nick from users where user_id IN (select authorized_users from users where user_id= $me['user_id']
				// $allAuthUsers = $userMdl->where(array('authorized_to' => $manager['user_id'])) ->getField('user_id, nick');
				// 更新session
				$manager['authorized_users'] = $allUserIds;
				session('manager', $manager);
				// 更新登录的user
				$data = array('authorized_users' => join(',', $allUserIds));
				$saveRes = $userMdl->where(array('user_id'=>$manager['user_id']))->save($data);
				if($saveRes === false) {
					throw_exception('DB异常: '. $userMdl->getDbError());
				}
				
				$userMdl->commit();
				
			} catch (Exception $e) {
				$userMdl->rollback();
				Log::record($e->getMessage());
				Log::record($e->getTraceAsString());
				Log::save();
				$this->error($e->getMessage());
			}
		}
		
		$this->authorized_users = $manager['authorized_users'];
		if($manager['type'] != '') {
			$this->authorized_users[$manager['nick']] = $manager['user_id'];
		}
		
		$this->nick = $manager['nick'];
		$this->display();
	}
	
    public function logout()
    {
        session('[destroy]');
        redirect("/");
    }

    /**
     * 获取用户实时消费信息
     * [当前余额 && 实时花费 && 其他实时指标(展现量、点击量……)]
     * @return string
     */
    public function getUserInfo()
    {
    	$user = session('me');
    	$uMdl = new UserModel;
    	$real_data = $uMdl->getUserRealTimeCost($user['nick']);
    	$balance = $uMdl->getUserBalance();
    	$real_data = object_to_array($real_data);

    	$userInfo = array();
    	$userInfo['yesterday_cost'] = D("RptCampaign")->getCost($this->me['user_id']);
		$userInfo['real_day_cost'] = isset($real_data['results']['rt_rpt_result_entity_d_t_o'][0]['cost']) ? (floatval($real_data['results']['rt_rpt_result_entity_d_t_o'][0]['cost'])/100) : 0;
		$userInfo['balance'] = isset($balance['balance']) ? $balance['balance'] : 0;
		$this->display_json($userInfo);
    }

    public function getAccountToken($user_id, $http)
    {
    	$url = build_url('authservice/tokens/'. $user_id);
    	$res = $http->get($url);
    	$token = $http->httpStatusCode != 200 ? '' : $res->access_token;
    	cookie('token', $token);
    	return true;
    }

}

/** 店铺状态 */
class SHOP_STATUS {
	/** 店铺状态： 没有店铺 */
	const NO_SHOP = 1;
	/** 店铺状态： 没有开通直通车他 */
	const NO_ZTC = 2; 
	const NO_SERVER = 3;
}